package controller

import (
	"StrayAnimals/internal/service"
	"StrayAnimals/pkg/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

// Login 用户登录接口
func Login(c *gin.Context) {
	var userInput struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}

	// 解析请求体
	if err := c.ShouldBindJSON(&userInput); err != nil {
		c.JSON(400, gin.H{
			"code":    401,
			"message": "参数错误；" + err.Error(),
		})
		return
	}

	// 验证邮箱格式
	if !utils.IsValidEmail(userInput.Email) {
		c.JSON(400, gin.H{
			"code":    402,
			"message": "邮箱格式不正确",
		})
		return
	}

	// 查询用户是否存在，并获取用户信息
	user, err := service.GetUserByEmail(userInput.Email)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			c.JSON(400, gin.H{
				"code":    403,
				"message": "邮箱未注册，请先注册",
			})
		} else {
			c.JSON(500, gin.H{
				"code":    501,
				"message": "系统错误，登录失败，请稍后再试；" + err.Error(),
			})
		}
		return
	}

	// 检查密码是否正确
	if err := service.CheckPassword(user.Password, userInput.Password); err != nil {
		if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
			c.JSON(400, gin.H{
				"code":    404,
				"message": "密码错误，请检查密码",
			})
		} else {
			c.JSON(500, gin.H{
				"code":    501,
				"message": "系统错误，登录失败，请稍后再试；" + err.Error(),
			})
		}
		return
	}

	// 生成 Token
	token, err := service.GenerateUserToken(user)
	if err != nil {
		c.JSON(500, gin.H{
			"code":    501,
			"message": "系统错误，登录失败，请稍后再试；" + err.Error(),
		})
		return
	}

	// 返回成功响应，包含 Token
	c.JSON(200, gin.H{
		"code":    200,
		"message": "登录成功",
		"data": gin.H{
			"user": gin.H{
				"id":        user.ID,
				"email":     user.Email,
				"phone":     user.Phone,
				"password":  userInput.Password,
				"username":  user.Username,
				"gender":    user.Gender,
				"birthday":  user.Birthday,
				"avatar":    user.Avatar,
				"isManager": user.IsManager,
			},
			"token": token,
		},
	})
}
